
// src/api/modules/stopwords.ts
import {
    getItems,
    getItemById,
    createItem,
    updateItem,
    updateItems,
    deleteItem,
    deleteItems,
} from "@/api/directus";

/** 集合名（与 Directus 中的 collection 一致） */
export const COLLECTION_STOPWORDS = "stopwords" as const;

/** 状态 */
export type StopwordStatus = "published" | "draft" | "archived";

/** 记录结构（Directus 默认字段 + 自定义字段） */
export interface StopwordItem {
    id: number | string;
    /** 停用词内容 */
    query?: string;
    /** 状态：published=启用、draft=停用、archived=删除 */
    status?: StopwordStatus;

    // 可选系统字段：是否有权限取决于角色设置
    date_created?: string;
    date_updated?: string;
    user_created?: any;
    user_updated?: any;
}

/** 列表入参 / 出参 */
export interface StopwordListParams {
    page?: number;                 // 默认 1
    pageSize?: number;             // 默认 25
    keyword?: string;              // 模糊搜索 query
    sort?: string | string[];      // 默认 -id（倒序）
    excludeStatus?: StopwordStatus;// 默认 "archived"（过滤掉已归档）
    signal?: AbortSignal;
}
export interface StopwordListResult {
    list: StopwordItem[];
    /** 过滤后的总数（使用 meta=filter_count 获取） */
    total: number;
}

/** 列表：GET /items/stopwords
 *  - 过滤：status != archived
 *  - 关键字：query _contains
 *  - 只取最小字段集（避免不必要的权限问题）
 *  - total 使用 filter_count（与 Directus 过滤条件保持一致）
 */
export async function listStopwords(
    params: StopwordListParams = {}
): Promise<StopwordListResult> {
    const {
        page = 1,
        pageSize = 25,
        keyword,
        sort = "-id",
        excludeStatus = "archived",
        signal,
    } = params;

    const filter: Record<string, any> = {};
    if (excludeStatus) filter.status = { _neq: excludeStatus };
    if (keyword && keyword.trim()) filter.query = { _contains: keyword.trim() };

    const fields = ["id", "query", "status"];
    const { data, meta } = await getItems<StopwordItem>(COLLECTION_STOPWORDS, {
        page,
        limit: pageSize,
        sort,
        fields,
        filter,
        meta: "filter_count",
        signal,
    });

    return {
        list: data,
        total: (meta as any)?.filter_count ?? 0,
    };
}

/** 详情：GET /items/stopwords/:id
 * 只取有用字段，尽量避免 date_* 权限报错；如果需要可自行在 fields 中加入。
 */
export function getStopwordById(id: number | string, signal?: AbortSignal) {
    return getItemById<StopwordItem>(COLLECTION_STOPWORDS, id, {
        fields: ["id", "query", "status"], // 如需时间字段可追加： "date_created","date_updated"
        signal,
    });
}

/** 新增：POST /items/stopwords */
export function createStopword(payload: Partial<StopwordItem>) {
    return createItem<StopwordItem>(COLLECTION_STOPWORDS, payload);
}

/** 更新（单条）：PATCH /items/stopwords/:id */
export function updateStopword(id: number | string, payload: Partial<StopwordItem>) {
    return updateItem<StopwordItem>(COLLECTION_STOPWORDS, id, payload);
}

/** 批量更新：PATCH /items/stopwords */
export function updateStopwords(rows: Array<Partial<StopwordItem> & { id: string | number }>) {
    return updateItems<StopwordItem>(COLLECTION_STOPWORDS, rows);
}

/** 启用 -> status=published */
export function enableStopword(id: number | string) {
    return updateStopword(id, { status: "published" });
}

/** 停用 -> status=draft */
export function disableStopword(id: number | string) {
    return updateStopword(id, { status: "draft" });
}

/** 物理删除（通常不建议，建议走 archived 软删，这里提供以备不时之需） */
export function removeStopword(id: number | string) {
    return deleteItem(COLLECTION_STOPWORDS, id);
}

/** 批量物理删除 */
export function removeStopwords(ids: Array<number | string>) {
    return deleteItems(COLLECTION_STOPWORDS, ids);
}
